package Net.list;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import Config.GeneralsConfig;
import baidupcs.api.BaiduPcs;
import baidupcs.auth.AccessToken;
import baidupcs.auth.BaiduPcsAuth;
import baidupcs.error.auth.BaiduPcsAuthException;
import baidupcs.error.auth.InvalidArgsException;
import baidupcs.error.auth.NoRefreshTokenException;
import baidupcs.response.api.FileMetaWithExtra;
import baidupcs.util.BaiduUtil;

public class GetList {

    private final static Logger logger = LogManager.getLogger(GetList.class.getName());

    /**
     * 获取命令，并加入数据库
     *
     * @throws SQLException
     *             添加命令出错
     *
     * @create 2014.11.03
     * @latest 2014.11.03
     *
     * @author sundaydx
     * @since 2.0.1
     * @version 2.0.1
     */
    public static ArrayList<String> getList() {
        logger.info("进行获取远程目录");
        return getOrders();
    }

    /**
     * 从网络获取Orders文件夹列表，读取最早的命令
     *
     * @return String 对象，最早的命令内容
     *
     * @create 2014.11.03
     * @latest 2014.11.03
     *
     * @author sundaydx
     * @since 2.0.1
     * @version 2.0.1
     */
    private static ArrayList<String> getOrders() {
           try {
            AccessToken ac = (AccessToken) BaiduUtil.fromString(GeneralsConfig.stringAcToken);
            
            ac = BaiduPcsAuth.validateToken(ac);
            BaiduPcs pcs = new BaiduPcs(ac);
            
            
            List<FileMetaWithExtra> lists = pcs.list("/");
            ArrayList<String> tmp = new ArrayList<String>();
            
            for(FileMetaWithExtra t : lists) {
                if(t.isDir())
                    tmp.add(t.getFileName());
            }
            
            return tmp;
            
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidArgsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BaiduPcsAuthException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoRefreshTokenException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
